package all.controller;

import all.pojo.Course;
import all.pojo.SelfInfo;
import all.utils.B64;
import all.utils.RSAEncoder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.transform.Source;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;


@Controller
@RequestMapping("/login")
public class LoginController {

    private String astuNum = null;
    private String apassword = null;
    private List<Course> list1=null;
    private List<Course> list2=null;
    private List<Course> list3=null;
    private List<Course> list4=null;

    //登陆接口，成功返回所有成绩，不成功返回一个值全部为0的course对象存在list里面
    @ResponseBody
    @RequestMapping("login")
    public List<List<Course>> login(Model model, @RequestParam(name = "username", required = true) String stuNum, @RequestParam(name = "password", required = true) String password) throws InterruptedException, ExecutionException, IOException {
        int flage;
        List<List<Course>> flaselist = new ArrayList<List<Course>>();
        try {
            astuNum = stuNum;
            apassword = password;

            String url = "http://jwxt.hbnu.edu.cn";
            Map<String, String> cookies = new HashMap<>();
            String modulus;
            String exponent;
            String csrftoken;
            Connection connection;
            Connection.Response response;
            Document document;

            connection = Jsoup.connect(url + "/xtgl/login_slogin.html?language=zh_CN&_t=" + new Date().getTime());
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
            response = connection.execute();
            cookies = response.cookies();
            //保存csrftoken
            document = Jsoup.parse(response.body());
            csrftoken = document.getElementById("csrftoken").val();
            connection = Jsoup.connect(url + "/xtgl/login_getPublicKey.html?time=" + new Date().getTime() + "&_=" + new Date().getTime());
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
            response = connection.cookies(cookies).ignoreContentType(true).execute();
            JSONObject jsonObject = JSON.parseObject(response.body());
            modulus = jsonObject.getString("modulus");
            exponent = jsonObject.getString("exponent");
            password = RSAEncoder.RSAEncrypt(password, B64.b64tohex(modulus), B64.b64tohex(exponent));
            password = B64.hex2b64(password);

            connection = Jsoup.connect(url + "/xtgl/login_slogin.html?time=" + new Date().getTime());
            connection.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");

            connection.data("csrftoken", csrftoken);
            connection.data("yhm", stuNum);
            connection.data("mm", password);
            connection.data("mm", password);
            Map<String, String> datas = new HashMap<>();
            datas.put("xnm", "");
            datas.put("xqm", "");
            datas.put("_search", "false");
            datas.put("nd", String.valueOf(new Date().getTime()));
            datas.put("queryModel.showCount", "100");
            datas.put("queryModel.currentPage", "1");
            datas.put("queryModel.sortName", "");
            datas.put("queryModel.sortOrder", "asc");
            datas.put("queryModel.sortName", "");
            datas.put("time", "0");

            connection.cookies(cookies).ignoreContentType(true)
                    .method(Connection.Method.POST).execute();
            connection.url(url + "/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005");
            response = connection.data(datas).execute();
            JSONObject jsonObject1 = JSON.parseObject(response.body());
            JSONArray gradeTable = JSON.parseArray(jsonObject1.getString("items"));
            JSONObject lesson = null;
            int first;
            int two;
            int three;
            int four;
            Course c1;
            Course c2;
            Course c3;
            Course c4;
            list1 = new ArrayList<>();
            list2 = new ArrayList<>();
            list3 = new ArrayList<>();
            list4 = new ArrayList<>();
            List<List<Course>> list = new ArrayList<>();
            for (Iterator iterator = gradeTable.iterator(); iterator.hasNext(); ) {
                lesson = (JSONObject) iterator.next();
                first = Integer.parseInt(lesson.getString("njmc")) + 1;
                two = Integer.parseInt(lesson.getString("njmc")) + 2;
                three = Integer.parseInt(lesson.getString("njmc")) + 3;
                four = Integer.parseInt(lesson.getString("njmc")) + 4;
                if (lesson.getString("xnmmc").contains(lesson.getString("njmc") + "-" + first)) {
                    String kcmc = lesson.getString("kcmc");//课程名
                    String jsxm = lesson.getString("jsxm");//老师
                    Double bfzcj = Double.valueOf(lesson.getString("bfzcj"));//分数
                    Double jd = Double.parseDouble(lesson.getString("jd"));//绩点
                    Double xf = Double.valueOf(lesson.getString("xf"));//学分
                    c1 = new Course(xf, bfzcj, jd, kcmc, jsxm);
                    list1.add(c1);
                } else if (lesson.getString("xnmmc").contains(first + "-" + two)) {
                    String kcmc = lesson.getString("kcmc");//课程名
                    String jsxm = lesson.getString("jsxm");//老师
                    Double bfzcj = Double.valueOf(lesson.getString("bfzcj"));//分数
                    Double jd = Double.parseDouble(lesson.getString("jd"));//绩点
                    Double xf = Double.valueOf(lesson.getString("xf"));//学分
                    c2 = new Course(xf, bfzcj, jd, kcmc, jsxm);
                    list2.add(c2);
                } else if (lesson.getString("xnmmc").contains(two + "-" + three)) {
                    String kcmc = lesson.getString("kcmc");//课程名
                    String jsxm = lesson.getString("jsxm");//老师
                    Double bfzcj = Double.valueOf(lesson.getString("bfzcj"));//分数
                    Double jd = Double.parseDouble(lesson.getString("jd"));//绩点
                    Double xf = Double.valueOf(lesson.getString("xf"));//学分
                    c3 = new Course(xf, bfzcj, jd, kcmc, jsxm);
                    list3.add(c3);
                } else if (lesson.getString("xnmmc").contains(three + "-" + four)) {
                    String kcmc = lesson.getString("kcmc");//课程名
                    String jsxm = lesson.getString("jsxm");//老师
                    Double bfzcj = Double.valueOf(lesson.getString("bfzcj"));//分数
                    Double jd = Double.parseDouble(lesson.getString("jd"));//绩点
                    Double xf = Double.valueOf(lesson.getString("xf"));//学分
                    c4 = new Course(xf, bfzcj, jd, kcmc, jsxm);
                    list4.add(c4);
                } else {
                    System.out.println("数据查询结束");
                }
            }
            list.add(list1);
            list.add(list2);
            list.add(list3);
            list.add(list4);
            return list;
        } catch (Exception e) {
            Course course = new Course(0.00,0.00,0.00,"0","0");
            List<Course> flist = new ArrayList<Course>();
            flist.add(course);
            flaselist.add(flist);
            return flaselist;
        }
    }


    //个人信息接口，返回个人信息，需要先完成登陆请求才可以访问
    @ResponseBody
    @RequestMapping("selfinfo")
    public SelfInfo selfinfo() throws InterruptedException, ExecutionException, IOException {

        String url = "http://jwxt.hbnu.edu.cn";
        Map<String, String> cookies = new HashMap<>();
        String modulus;
        String exponent;
        String csrftoken;
        Connection connection;
        Connection.Response response;
        Document document;

        connection = Jsoup.connect(url + "/xtgl/login_slogin.html?language=zh_CN&_t=" + new Date().getTime());
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        response = connection.execute();
        cookies = response.cookies();
        //保存csrftoken
        document = Jsoup.parse(response.body());
        csrftoken = document.getElementById("csrftoken").val();
        connection = Jsoup.connect(url + "/xtgl/login_getPublicKey.html?time=" + new Date().getTime() + "&_=" + new Date().getTime());
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        response = connection.cookies(cookies).ignoreContentType(true).execute();
        JSONObject jsonObject = JSON.parseObject(response.body());
        modulus = jsonObject.getString("modulus");
        exponent = jsonObject.getString("exponent");
        apassword = RSAEncoder.RSAEncrypt(apassword, B64.b64tohex(modulus), B64.b64tohex(exponent));
        apassword = B64.hex2b64(apassword);


        connection = Jsoup.connect(url + "/xtgl/login_slogin.html?time=" + new Date().getTime());
        connection.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");

        connection.data("csrftoken", csrftoken);
        connection.data("yhm", astuNum);
        connection.data("mm", apassword);
        connection.data("mm", apassword);
        connection.cookies(cookies).ignoreContentType(true)
                .method(Connection.Method.POST).execute();

        connection.url(url + "/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801&layout=default&su=" + astuNum);
        response = connection.execute();
        document = Jsoup.parse(response.body());

        String stuNo = document.select("div.col-sm-8 p.form-control-static").first().text();//学号
        String studentName = document.select("div.col-sm-8 p.form-control-static").get(1).text();//姓名
        String college = document.select("div.col-sm-8 p.form-control-static").get(15).text();//学院
        String major = document.select("div.col-sm-8 p.form-control-static").get(16).text();//专业
        String classs = document.select("div.col-sm-8 p.form-control-static").get(18).text();//班级

        SelfInfo selfInfo = new SelfInfo(classs, studentName, college, major, stuNo);
        return selfInfo;
    }

    //加权平均分接口，返回四年的加权平均分，需要先完成登陆请求才可以访问
    @ResponseBody
    @RequestMapping("jqcourse")
    public List jqcourse() throws Exception {
        Double jqcourse1;
        Double jqcourse2;
        Double jqcourse3;
        Double jqcourse4;
        Double a1=0.00;
        Double a2=0.00;
        Double a3=0.00;
        Double a4=0.00;
        Double b1=0.00;
        Double b2=0.00;
        Double b3=0.00;
        Double b4=0.00;
        List list=new ArrayList();
        for (Course course : list1) {
            a1 = (course.getCredit() * course.getGrade()) + a1;
            b1 = course.getCredit() + b1;
        }
        for (Course course : list2) {
            a2 = (course.getCredit() * course.getGrade()) + a2;
            b2 = course.getCredit() + b2;
        }
        for (Course course : list3) {
            a3 = (course.getCredit() * course.getGrade()) + a3;
            b3 = course.getCredit() + b3;
        }
        for (Course course : list4) {
            a4 = (course.getCredit() * course.getGrade()) + a4;
            b4 = course.getCredit() + b4;
        }
        jqcourse1=a1/b1;
        jqcourse2=a2/b2;
        jqcourse3=a3/b3;
        jqcourse4=a4/b4;
        list.add(jqcourse1);
        list.add(jqcourse2);
        list.add(jqcourse3);
        list.add(jqcourse4);
        return list;
    }
}
